package JavaAboutInterview;

/**
 * @author:周鹏
 * @date: 2020/12/11 11:28
 * @description:
 */
class Lock implements Runnable{
    private boolean flag;
    private  Object obj1 = new Object();
    private Object obj2 = new Object();
    public Lock(boolean flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
        if (flag){
            while(true){
                deadLockab();
            }
        }else{
            while(true){
                deadLockba();
            }
        }
    }

    private void deadLockab() {
        String name = Thread.currentThread().getName();
        synchronized (obj1){
            System.out.println(name+"...lock on "+obj1);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (obj2){
                System.out.println(name+"...lock on "+obj2);
            }
        }
    }

    private void deadLockba() {
        String name = Thread.currentThread().getName();
        synchronized (obj2){
            System.out.println(name+"...lock on "+obj2);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (obj1){
                System.out.println(name+"...lock on "+obj1);
            }
        }
    }

}

public class DeadLockDemo2 {
    public static void main(String[] args) {
        Thread t1 = new Thread(new Lock(true));
        Thread t2 = new Thread(new Lock(false));
        t1.start();
        t2.start();
    }

}
